<template>
  <div class="home">

    <notify :data='notifyList'
            v-if='notifyList&&notifyList.broadcasts.length'
            ref='refsNotify' />
    <my-Header ref="bgImage" />

    <scroll :data="goodsList"
            @scroll="scroll"
            :listen-scroll="listenScroll"
            :probe-type="probeType"
            ref="list"
            class="scroll-list  scroll-min ">
      <div>
        <sidebar ref="sidebar"
                 v-if='classData'
                 @change='sidebarChange'
                 :classData='classData' />

        <transition name="fade">

          <div class="list-wrap"
               v-if='goodsList.length'>

            <div class='item-wrap'
                 v-for="(item,index) in goodsList"
                 :key='index'>

              <item ref='listItem'
                    :item='items'
                    :resData='resData'
                    v-for="(items) in item"
                    @change='buyChange'
                    @show='_getItemDetail'
                    :key="items.alias" />

              <!-- 架子 -->
              <div class='frame-row'>
                <div></div>
              </div>
            </div>

            <!-- 无产品展示 -->
            <div class='no-product'
                 v-show='resData&&!goodsList.length'>
              <img src="@/assets/nobox@2x.74a1419.png"
                   alt="">
              <div>
                没有商品哦，去其他分类看看吧
              </div>
              <div @click="sidebarChange('')">
                所有商品
              </div>
            </div>
          </div>
          <!-- 回调为空 -->
          <div class="list-wrap"
               v-else-if='resData'>
            <div class='empty'>抱歉！没有找到您要的信息</div>
          </div>
        </transition>
      </div>
    </scroll>
    <product-detail :isShow='isShowDetail'
                    :item='itemDetailData'
                    @change='clickDetailBuy'></product-detail>
    <pop-buy :pop='respond'
             :isActivity='resData.isActivity'
             :buyItem='buyItem'></pop-buy>
    <!-- 现金红包 -->
    <pop-cash v-model='isPopCash'
              v-if='!visibleDT'></pop-cash>
    <div class='not-initiated'
         v-if='abnormal'>
      <div>
        <img src="@/assets/err_img.png"
             alt="">
      </div>
      <div ref='errText'
           class='text'>
        设备 : {{resData.mainboardNo}}
        {{abnormalText}} <img :src="require('@/assets/cry@2x.png')" /><br>
        <p>亲，可到隔壁村订购（1栋~6栋都有水趣驿站）</p>
      </div>
    </div>
    <dt-attention v-model="visibleDT"></dt-attention>

 
  </div>
</template>

<script>
// @ is an alias to /src

function freight () {

  setTimeout(() => {
    console.log('授权回调', vm);
    vm.isShowIframe = false;
    let iframeWindow = document.querySelector("#other-iframe");
    console.log(123, iframeWindow);
  }, 1000);


}



import Scroll from '@/components/Scroll/';
import { prefixStyle } from '@/common/js/dom';
import { init } from '@/common/js/globalJs.js'
import { findContainers, findProductClass, findVendorBroadcast, vendorLoginfind, payWxConfig } from '@/api';
import { mapMutations } from 'vuex'
const transform = prefixStyle('transform')
let vm = null;
export default {
  data () {
    return {
      resData: '',
      classData: '',
      visibleDT: this.$route.query.isEvaluate ? true : false,
      goodsList: [],
      isPopCash: true,//是否启动现金弹出
      scrollY: 0,
      respond: false,
      buyItem: '',
      isShowDetail: false,
      itemDetailData: "",
      abnormal: false,//柜子异常显示
      abnormalText: '',//错误语言
      notifyList: '',//系统通知
      domTitle: '',
      isShowIframe: true,
    }
  },

  components: {
    myHeader: () => import('./myHeader'),
    Scroll,
    sidebar: () => import('./sidebar'),
    item: () => import('./item'),
    popCash: () => import('./popCash'),
    popBuy: () => import('./popBuy'),
    productDetail: () => import('./productDetail'),
    notify: () => import('./notify'),
    dtAttention: () => import('@/components/AttDT'),

  },
  watch: {
    scrollY (newVal) {


      let scale = 1
      let zIndex = 0
      let blur = 0
      const percent = Math.abs(newVal / this.imageHeight)
      if (newVal > 0) {
        scale = 1 + percent
        zIndex = 10
        this.$refs.bgImage.$el.style['filter'] = 'none'
      } else {
        blur = Math.min(20 * percent, 20);



        this.$refs.bgImage.$el.style['filter'] = `blur(${blur}px)`
        this.$refs.bgImage.$el.style['webkit-flter'] = `blur(${blur}px)`
      }
      this.$refs.bgImage.$el.style.zIndex = zIndex
    },
    resData (n) {
      this.handlePageData(n);
    },
    domTitle (n) {
      document.title = n;
    }

  },
  created () {
    this.probeType = 3
    this.listenScroll = true
    this.getFindContainers();//商品列表 
    this.getfindProductClass();//分类列表
    this.getNotify();//系统通知
    this.getIsVip();//获取用户信息 判断贵宾
    this.getPayParames();//获取支付参数
    window.freight = function () {

      setTimeout(() => {
        console.log('授权回调', vm);
        vm.isShowIframe = false;
        let iframeWindow = document.querySelector("#other-iframe");
        console.log(123, iframeWindow);
      }, 1000);


    }
  },
  // 计算获取背景图片高度 设置scroll的偏移值
  mounted () {



    let fontSize = parseFloat(getComputedStyle(window.document.documentElement)['font-size']);
    this.$nextTick(function () {

      this.imageHeight = 4.266667 * fontSize// this.$refs.bgImage.$el.clientHeight
      let that = this;
      this.$refs.list.$el.style.top = `${4.266667 * fontSize}px`
    })
    vm = this;


  },
  methods: {
    scroll (pos) {
      this.scrollY = pos.y
    },
    /**商品分类 */
    getfindProductClass () {
      findProductClass().then(res => {
         res.productClass.unshift({
           classId:-1,
           className:'全部'
         })
         console.log(res.productClass);
         
        this.classData = res.productClass
      })
    },
    /**系统通知 */
    getNotify () {
      findVendorBroadcast().then(res => {
        this.notifyList = res;
        if (res.broadcasts.length) {
          let num = parseFloat(this.$refs.list.$el.style.top);
          let nHei = parseFloat(getComputedStyle(window.document.documentElement)['font-size']) *
            0.853333;
          this.$refs.list.$el.style.top = num + nHei + 'px';
        }

      })
    },
    /**货柜机数据 */
    getFindContainers () {
      this.loading.open('加载中...');
      findContainers({ classId: this.classId }).then(res => {
        if(!res){return};
        if (!this.domTitle) {
          if (res.containerName) {
            this.domTitle = '水趣驿站—' + res.containerName;
          } else {
            this.domTitle = '水趣驿站'
          }

        }

        this.resData = res;
        this.loading.close();
      }).catch(function (error) {
        this.loading.close();
      })
    },
    /**获取用户权限 */
    getIsVip () {
      vendorLoginfind().then(res => {
        this.setUserInfo(res.userInfo);

      })
    },
    /**获取微信支付需要的参数 */
    getPayParames () {
      payWxConfig().then(res => {
        init(res.appId, Number(res.timestamp), res.nonceStr, res.signature);
      })
    },
    /**数据格式处理 */
    handlePageData (data) {

      let list = data.vendorMainboardContainers[0].vendorDoorProucts;
      //异常处理
      if (!data.isOperation) {
        this.abnormal = true;//异常显示
        this.abnormalText = '尚未启动'
      } else if (list) {

        //商品正常销售   
        //随便抓取一个商品判断身上的状态 
        // 货柜状态：0未激活，后台可以撤回分配；1激活，空闲中；2运行中；3报损中；4补货中
        if (list.length == 0 || list[0].containerStatus == 2) {
          let bigArr = []
          let nArr = []
          if (list.length == 20) {
            list.splice(7, 0, { placeholder: true })
          }
          for (let i = 0; i < list.length; i++) {
            const element = list[i];
            nArr.push(list[i])
            if ((i + 1) % 3 == 0) {
              bigArr.push(nArr)
              nArr = []
            }
            if (list.length % 3 && i == list.length - 1) {
              bigArr.push(nArr)
            }
          }
          this.goodsList = bigArr;

          return;
        } else if (list[0].containerStatus == 3) {
          this.abnormal = true;//异常显示
          this.abnormalText = '正在抢修中。'
        }
        else if (list[0].containerStatus == 4) {
          this.abnormal = true;//异常显示
          this.abnormalText = '正在补货中，请稍后'
        }
        else if (list[0].containerStatus == 1) {
          this.abnormal = true;//异常显示
          this.abnormalText = '设备处于空闲状态'
        } else {
          this.abnormal = true;//异常显示
          this.abnormalText = '设备尚未初始化'
        }
        document.getElementsByClassName('my-tab')[0].style.display = 'none';
      }

    },
    /**切换分类 */
    sidebarChange (item) {
      this.classId = item.classId
      this.getFindContainers()
    },
    /**弹出购买窗口 */
    buyChange (item) {
      this.buyItem = item
      this.respond = !this.respond;

    },
    _getItemDetail (item) {
      this.isShowDetail = !this.isShowDetail
      this.itemDetailData = item
    },
    clickDetailBuy (item) {
      this.buyChange(item);
    },
    ...mapMutations({
      setUserInfo: "SET_USERINFO",

    }),

  },

  activated () {
    if (this.resData) {
      document.title = this.domTitle;
      this.getFindContainers()
    }

  }

};
</script>

<style lang="scss">
@import "@/common/scss/mixin.scss";

.home {
  .scroll-min {
    > div {
      min-height: 500px;
      background: $color-background-d;
    }
  }
  .list-wrap {
    padding: 16px 0;
    background: $color-background-d;
    min-height: 300px;
    &::after {
      display: block;
      content: "";
      height: 1px;
      width: 100%;
      clear: both;
    }
    .empty {
      @include fjc;
      height: 400px;
    }
    .item-wrap {
      position: relative;
      padding: 0 16px;
      display: flex;

      &::after {
        display: block;
        content: "";
        height: 1px;
        width: 100%;
        clear: both;
      }
      .home-item:nth-child(3n + 3) {
        margin-right: 0;
      }
      .frame-row {
        position: absolute;
        bottom: 27px;
        left: 0;
        width: 100%;
        height: 60px;
        z-index: 9;
        border-bottom: 12px solid #c7c7c7;
        box-sizing: border-box;
        opacity: 1;
        animation: myOpacity 5s;

        > div {
          background: #e4e4e4;
          height: 48px;
          width: 100%;
          border-radius: 50px 50px 0 0;
        }
      }
    }
    .no-product {
      padding-top: 150px;
      img {
        width: 220px;
      }
      > div:nth-child(2) {
        color: #979797;
        margin-top: 12px;
        font-size: 24px; /*px*/
      }
      > div:last-child {
        width: 176px;
        height: 64px;
        border: 2px solid rgba(51, 51, 51, 1);
        border-radius: 64px;
        margin: auto;
        line-height: 64px;
        margin-top: 52px;
        font-size: 28px; /*px*/
      }
    }
  }
  .not-initiated {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #fff;
    @include fjc;
    flex-flow: row wrap;
    align-content: center;
    z-index: 30;
    div {
      width: 100%;
      img {
        width: 220px;
      }
    }
    > .text {
      line-height: 44px;
      font-size: 28px; /*px*/
      color: #111;
      p {
        padding-top: 20px;
      }
      img {
        margin-left: 20px;
        width: 60px;
      }
    }
  }
}
 
@keyframes myOpacity {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>

